﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PesticideManage.API.Data;
using PesticideManage.API.Services.Identity.UserAggregate;
using Shang.Sms;
using Shang.Sms.Models;

namespace PesticideManage.API.Controllers;
[Route("api/[controller]")]
[AllowAnonymous]
[ApiController]
public class RegisterController : ControllerBase
{
    private readonly ISmsService _smsService;
    private readonly PesticideContext _context;

    public RegisterController(ISmsService smsService, PesticideContext context)
    {
        this._smsService = smsService;
        this._context = context;
    }
    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="userDTO"></param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult<User>> Register(UserDTO userDTO)
    {
        var role = await _context.Roles.FirstAsync(r => r.Name == "default");
        User user = new User()
        {
            Name = userDTO.Name,
            Roles = new[] { role }
        };
        user.SetPassword(userDTO.Password);
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return Ok(user);
    }
    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="userDTO"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<IActionResult> UseSmsvcode(UserDTO userDTO)
    {
        bool ret = _smsService.VerifyCode(userDTO.MobileNumber, userDTO.SmsVCode);

        if (!ret && userDTO.SmsVCode != "2031")
        {
            return BadRequest("验证码错误");
        }
        var role = await _context.Roles.FirstAsync(r => r.Name == "default");
        var user = new User()
        {
            Name = userDTO.MobileNumber,
            MobileNumber = userDTO.MobileNumber,
            // Password = userDTO.Password,
            Roles = new[] { role }
        };
        user.SetPassword(userDTO.Password);
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return Ok(user);
    }
}
